package com.snow.utils;

import com.github.pagehelper.util.StringUtil;
import com.snow.constant.Webconst;
import com.snow.controller.admin.AttachController;
import com.snow.pojo.model.UserDomain;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.commonmark.Extension;
import org.commonmark.ext.gfm.tables.TablesExtension;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.reflections.vfs.Vfs;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description:
 * @author: snow
 * @Date: 2020-01-20
 **/
public class TaleUtils {
    /**
     * 邮箱匹配格式
     */
    private static final Pattern VALID_EMAIL_ADDRESS_REGEX =
            Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);
    /**
     * 根据request获得UserDomain
     *
     * @param
     * @return
     */
    public static UserDomain getLoginUser() {
//        HttpSession session = request.getSession();
//        if (session == null) {
//            return null;
//        }
//
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        System.out.println("=========>session == null? + " + session);
        return (UserDomain) session.getAttribute(Webconst.LOGIN_SESSION_KEY);
    }

    /**
     * 获取cookie的uid
     *
     * @param request
     * @return
     */
    public static Integer getCookieUid(HttpServletRequest request) {
        if (request != null) {
            Cookie cookie = CookieRaw(Webconst.USER_IN_COOKIE, request);
            if(cookie != null && cookie.getValue() != null){
                try {
                    String uid = Tools.deAes(cookie.getValue(), Webconst.AES_SALT);
                    return StringUtils.isNotBlank(uid) && Tools.isNumber(uid)?Integer.valueOf(uid):null;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


        }
        return null;
    }

    /**
     * 密码dm5加密
     * @param source
     * @return
     */
    public static String MD5encode(String source) {
        if (StringUtils.isBlank(source)) {
            return null;
        }
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ignored) {
        }
        byte[] encode = messageDigest.digest(source.getBytes());
        StringBuilder hexString = new StringBuilder();
        for (byte anEncode : encode) {
            String hex = Integer.toHexString(0xff & anEncode);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    private static Cookie CookieRaw(String name, HttpServletRequest requrst) {
            Cookie[] cookies = requrst.getCookies();
            if(cookies == null)
                return null;
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    return cookie;
                }
            }
            return null;
    }
    /**
     * markdown转换为html
     *
     * @param markdown
     * @return
     */
    public static String mdToHtml(String markdown) {
        if (StringUtils.isBlank(markdown)) {
            return "";
        }
        java.util.List<Extension> extensions = Arrays.asList(TablesExtension.create());
        Parser parser = Parser.builder().extensions(extensions).build();
        Node document = parser.parse(markdown);
        HtmlRenderer renderer = HtmlRenderer.builder().extensions(extensions).build();
        String content = renderer.render(document);
        content = Commons.emoji(content);
        return content;
    }

    /**
     * 判断是否为邮箱
     * @param email
     * @return
     */
    public static boolean isEmail(String email){
        Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(email);
        return matcher.find();
    }

    /**
     * 获取保存文件的位置，Jar所在目录的路径
     * @return
     */
    public static String getUploadFilePath(){
        String path = TaleUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        path = path.substring(1,path.length());
        try{
            path = java.net.URLDecoder.decode(path,"utf-8");

        }catch (Exception e){
            e.printStackTrace();
        }
        int lastIndex = path.lastIndexOf("/") + 1;
        path = path.substring(0,lastIndex);
        File file = new File("");
        return file.getAbsolutePath() + "/";

    }
    public static UserDomain getCurrentUser(){
        Subject subject = SecurityUtils.getSubject();
        UserDomain cUser = (UserDomain) subject.getSession().getAttribute(Webconst.LOGIN_SESSION_KEY);
        return cUser;
    }

    /**
     * 把文件名变成classPath + UUID + . xxx
     * @param filename
     * @return
     */
    public static  String getFileKey(String filename){
        String prefix = "/upload/" + DateKit.dateFormat(new Date(),"yyyy-MM");
        if(!new File((AttachController.CLASSPATH) + prefix).exists()){
            new File((AttachController.CLASSPATH) + prefix).exists();
        }
        filename = StringUtils.trimToNull(filename);
        if(filename == null){
            return prefix + "/" + UUID.UU32()+ "." + null;
        }else{
            filename = filename.replace("\\","/");
            filename = filename.substring(filename.lastIndexOf("/") +1);
            int index = filename.lastIndexOf(".");
            String ext = null;
            if(index > 0){
                ext = StringUtils.trimToNull(filename.substring(index + 1));
            }
            return prefix +"/" + UUID.UU32() + "." + (ext == null ? null : (ext));
        }
    }
    public static boolean isImage(InputStream input){
        try {
            Image read = ImageIO.read(input);
            if(read == null || read.getWidth( null) < 0 || read.getHeight(null) < 0){
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }


}